package com.scpii.universal.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.TriggersRemove;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.dto.ViewAttributeDto;
import com.scpii.universal.dto.ViewCateRelationDto;
import com.scpii.universal.hibernate.dao.AppPageDao;
import com.scpii.universal.hibernate.dao.AppPageViewDao;
import com.scpii.universal.hibernate.dao.AppViewCatelogRalationDao;
import com.scpii.universal.hibernate.dao.AttributeDao;
import com.scpii.universal.hibernate.dao.AttributeValueDao;
import com.scpii.universal.hibernate.dao.BindContentAttributeDao;
import com.scpii.universal.hibernate.dao.CatelogDao;
import com.scpii.universal.hibernate.dao.ContentDao;
import com.scpii.universal.hibernate.dao.ViewContentAttributeDao;
import com.scpii.universal.hibernate.entity.AppPageTab;
import com.scpii.universal.hibernate.entity.AppPageViewTab;
import com.scpii.universal.hibernate.entity.AppViewCatelogRalationTab;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.ViewContentAttributeTab;
import com.scpii.universal.service.CatelogService;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;

/**
 * universalWeb
 * @author liuhj
 * 2012-7-5下午05:17:53
 */
@Service
public class CatelogServiceImpl extends BaseServiceImpl<CatelogTab, Integer> implements
		CatelogService {
	@Resource
	private CatelogDao catelogDao;
	@Resource
	private AttributeDao attributeDao;
	@Resource
	private ContentDao contentDao;
	@Resource
	private AppViewCatelogRalationDao appViewCatelogRalationDao;
	@Resource
	private AppPageDao appPageDao;
	@Resource
	private AppPageViewDao appPageViewDao;
	@Resource
	private ViewContentAttributeDao viewContentAttributeDao;
	@Resource
	private AttributeValueDao attributeValueDao;
	@Resource
	private BindContentAttributeDao bindContentAttributeDao;
	private Log log = LogFactory.getLog(this.getClass());
	
	@Resource
	public void setBaseDao(CatelogDao catelogDao) {
		super.setBaseDao(catelogDao);
	}
	
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public List<CatelogTab> getAllCatelogs(Integer intEnterpId,Integer intAppId) {
		StringBuffer hql = new StringBuffer("from CatelogTab c ");
		hql.append("where c.intEnterpId=:intEnterpId and c.intAppId=:intAppId and c.intDeleteSign=:intDeleteSign");
		Map<String,Object> argsMap = new HashMap<String,Object>();
		argsMap.put("intEnterpId", intEnterpId);
		argsMap.put("intAppId", intAppId);
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		return catelogDao.hqlGetList(hql.toString(), argsMap);
	}
	
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public Integer save(CatelogTab catelogTab,UserInfoDto user){
		catelogTab.setIntAppId(user.getAppId());
		catelogTab.setIntEnterpId(user.getIntEnterpId());
		catelogTab.setIntHasSubCate(GenericConstants.IS_HAS_LEAF_NO);
		catelogTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		catelogTab.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		return catelogDao.save(catelogTab);
	}
	
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public Integer save(String jsonData, UserInfoDto user, String webAppsRealPath, String imgBasePath) {
		JSONObject jo = JSONObject.fromObject(jsonData);
		if(log.isDebugEnabled()){
			log.debug("保存分类的json请求数据:"+jo.toString());
		}
		CatelogTab catelog = (CatelogTab) JSONObject.toBean(jo.getJSONObject("catelogInfo"),CatelogTab.class);
		if ("\"null\"".equals(catelog.getVarCateImgUrl())){
			catelog.setVarCateImgUrl(null);
		}
		if (!StringUtils.isBlank(catelog.getVarCateImgUrl())) {
			catelog.setVarCateImgUrl(catelog.getVarCateImgUrl().replace(getServerUrl(), ""));
			copyIconFromTemp(webAppsRealPath, imgBasePath, catelog);
		}
		//保存分类
		int catelogId = this.save(catelog, user);
		
		//更新父节点HasSubCate字段
		int parentHasSubCate;
		if (catelog.getIntParentCateId() != 0 ) {
			parentHasSubCate = catelogDao.getCatelogInfoById(
					catelog.getIntParentCateId(),
					new String[] { "intCateId", "intHasSubCate" }).getIntHasSubCate();
			if (parentHasSubCate == GenericConstants.IS_HAS_LEAF_NO) {
				catelogDao.updateParentHasSubCate(catelog.getIntParentCateId(),GenericConstants.IS_HAS_LEAF_YES);
				log.info("更新父节点"+catelog.getIntParentCateId()+"为有子节点");
			}
		} else {
			parentHasSubCate = 0;
		}
		
		//检测父分类是否有引用，有则自动创建页面结构
		saveRelationsByCateId(catelog, catelogId, parentHasSubCate, user);
		
		JSONArray ja = JSONArray.fromObject(jo.get("attributeInfo"));
		int size = ja.size();
		for (int i = 0; i < size; i++) {
			//保存分类属性
			AttributeTab attribute = (AttributeTab) JSONObject
					.toBean(JSONObject.fromObject(ja.get(i)),AttributeTab.class);
			attribute.setIntCateId(catelogId);
			attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			attribute.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
			attribute.setIntInputType(GenericConstants.ATTRIBUTE_INPUT_TYPE_INPUT);
			attribute.setIntType(0);
			attributeDao.save(attribute);
			if(log.isDebugEnabled()){
				log.debug("保存分类-" + catelog.getVarCateName() + " 的属性："
						+ attribute.getVarAttriName());
			}
		}
		return catelogId;
	}
	
	/**
	 * 新增子分类时，父分类有引用，更新页面结构
	 * @param catelog
	 * @param subCateId
	 * @param parentHasSubCate
	 * @param user
	 * @author liuhj
	 * 2012-7-31下午11:51:03
	 */
	@Override
	public void saveRelationsByCateId(CatelogTab catelog,int subCateId,int parentHasSubCate,UserInfoDto user) {
		List<ViewCateRelationDto> referencedViews = appViewCatelogRalationDao
				.getRelationsByCateId(catelog.getIntParentCateId());
		if (referencedViews != null && referencedViews.size() > 0) {
			String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			//分类有被视图引用
			log.info("分类" + catelog.getIntParentCateId()
					+ "已经有视图引用了，新增子分类时会同时新增子页面、视图");
			for (ViewCateRelationDto viewCateRelationDto : referencedViews) {
				int modleStyleId = getStyleId(appPageViewDao.getViewInfoById(
						viewCateRelationDto.getIntViewId(),
						new String[] { "intViewId", "intModuleStyleId" })
						.getIntModuleStyleId());
				if (parentHasSubCate == GenericConstants.IS_HAS_LEAF_NO) {
					//分类没有叶子节点
					//新增子分类内容列表页面,title为添加分类名称
					Integer pageId = savePage(user, catelog.getVarCateName());
					//新增子分类视图
					savePageView(modleStyleId, pageId);
					//获取父分类视图对应跳转页面的视图[内容列表页面的视图]
					List<AppPageViewTab> views = appPageViewDao
							.getViewsInfoByPageId(viewCateRelationDto
									.getIntResourceId(),new String[] { "intViewId" }, false);
					int parentViewId = views.get(0).getIntViewId();
					//新增子分类视图分类对应,跳转页面ID为子分类的内容列表页面
					this.saveCatelogViewRelation(subCateId,parentViewId,pageId);
					//新增子分类 视图属性对应，和父分类视图属性对应相同
					List<ViewAttributeDto> parentViewAttributes = viewContentAttributeDao
							.getViewContentAttributes(viewCateRelationDto.getIntViewId());
					for (ViewAttributeDto viewAttributeDto : parentViewAttributes) {
						ViewContentAttributeTab vca = new ViewContentAttributeTab();
						vca.setDatUpdateDatetime(date);
						vca.setIntAttriId(viewAttributeDto.getIntAttriId());
						vca.setIntAttriOrder(viewAttributeDto.getIntAttriOrder());
						vca.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
						vca.setIntViewId(parentViewId);
						viewContentAttributeDao.save(vca);
					}
					// 修改父分类视图分类对应[下级类型]
					StringBuffer hql = new StringBuffer();
					hql.append("update AppViewCatelogRalationTab a set ");
					hql.append("a.intContentType=:intContentType,a.datUpdateDatetime=:datUpdateDatetime");
					hql.append(" where a.intViewCateId=:intViewCateId");
					Map<String,Object> argMaps = new HashMap<String,Object>();
					argMaps.put("intContentType",GenericConstants.NEXT_PAGE_CONTENT_TYPE_CATE );
					argMaps.put("datUpdateDatetime",date );
					argMaps.put("intViewCateId", viewCateRelationDto.getIntViewCateId());
					appViewCatelogRalationDao.hqlOperation(hql.toString(), argMaps);
				} else {
					//分类有叶子节点
					//新增子分类内容列表页面,title为子分类名称
					Integer pageId = savePage(user,catelog.getVarCateName());
					//新增子分类视图
					savePageView(modleStyleId,pageId);
					//获取父分类视图对应跳转页面的视图
					List<AppPageViewTab> views = appPageViewDao
							.getViewsInfoByPageId(viewCateRelationDto
									.getIntResourceId(),new String[] { "intViewId" }, false);
					//新增子分类视图分类对应,跳转页面ID为子分类的内容列表页面
					this.saveCatelogViewRelation(subCateId,views.get(0).getIntViewId(),pageId);
				}
			}
		}
	}
	
	/**
	 * 根据半风格获取全风格
	 * @param styleId
	 * @return
	 * @author liuhj
	 * 2012-8-21下午04:49:59
	 */
	private int getStyleId(int styleId) {
		switch (styleId) {
		case GenericConstants.LIST_STYLE_HALF_1:
			return GenericConstants.LIST_STYLE_FULL_1;
		case GenericConstants.LIST_STYLE_HALF_2:
			return GenericConstants.LIST_STYLE_FULL_2;
		case GenericConstants.LIST_STYLE_HALF_3:
			return GenericConstants.LIST_STYLE_FULL_3;
		case GenericConstants.GRID_STYLE_HALF_1:
			return GenericConstants.GRID_STYLE_FULL_2;
		case GenericConstants.GRID_STYLE_HALF_2:
			return GenericConstants.GRID_STYLE_FULL_1;
		case GenericConstants.GALLERY_STYLE_HALF_1:
			return GenericConstants.GALLERY_STYLE_FULL_1;
		case GenericConstants.GALLERY_STYLE_HALF_2:
			return GenericConstants.GALLERY_STYLE_FULL_2;
		case GenericConstants.GRID_STYLE_HALF_3:
			return GenericConstants.GRID_STYLE_FULL_3;
		default:
			return styleId;
		}
	}

	/**
	 * 保存页面视图
	 * @param modleStyleId
	 * @param pageId
	 * @return
	 * @author liuhj
	 * 2012-8-1上午12:29:52
	 */
	private Integer savePageView(int modleStyleId, int pageId) {
		AppPageViewTab view = new AppPageViewTab();
		view.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		view.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		view.setIntModuleStyleId(modleStyleId);// 视图模版
		view.setIntResourceId(pageId);//所属页面  
		view.setIntViewOrder(1);//顺序
		view.setIntViewBindDatatype(GenericConstants.BINDING_DATA_TYPE_CATELOG);
		Integer viewId = appPageViewDao.save(view);
		return viewId;
	}

	/**
	 * 保存页面
	 * @param user
	 * @param titleName
	 * @return
	 * @author liuhj
	 * 2012-8-1上午12:26:45
	 */
	private Integer savePage( UserInfoDto user,String titleName) {
		AppPageTab page = new AppPageTab();
		page.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		page.setIntAppId(user.getAppId());
		page.setIntEnterpId(user.getIntEnterpId());
		page.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		page.setVarTitleName(titleName);
		Integer pageId = appPageDao.save(page);
		return pageId;
	}
	
	/**
	 * 保存视图分类关联
	 * @param cateId
	 * @param viewId
	 * @return
	 * @author liuhj
	 * 2012-7-24下午05:25:32
	 */
	private Integer saveCatelogViewRelation(int cateId,int viewId,int pageId) {
		AppViewCatelogRalationTab relation = new AppViewCatelogRalationTab();
		relation.setIntCateId(cateId);
		relation.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		relation.setIntResourceId(pageId);//跳转页面
		relation.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		relation.setIntViewId(viewId);
		relation.setIntContentType(GenericConstants.NEXT_PAGE_CONTENT_TYPE_LIST);
		Integer relationId = appViewCatelogRalationDao.save(relation);
		return relationId;
	}
	
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void delete(Integer id) {
		List<CatelogTab> lstCatelogs = catelogDao.getSubordinateCatelogs(id);
		StringBuffer ids = new StringBuffer("(");
		if (lstCatelogs != null && lstCatelogs.size() > 0) {
			for (CatelogTab catelogTab : lstCatelogs) {
				ids.append(catelogTab.getIntCateId() + ",");
			}
			ids.deleteCharAt(ids.lastIndexOf(",")).append(")");
			//逻辑删除分类
			catelogDao.delete(ids.toString());
			log.info("删除分类及所有子分类");
			//删除分类内容
			contentDao.delete(ids.toString());
			log.info("删除分类及所有子分类的内容");
			//删除视图分类关联
			appViewCatelogRalationDao.delete(ids.toString());
			log.info("删除分类视图关联");
		}
		//判断删除该分类后，父分类是否还有子节点，没有则修改intHasSubCate状态
		CatelogTab catelog = catelogDao.getCatelogInfoById(id, new String[]{"intParentCateId"});
		if (catelog.getIntParentCateId() != 0) {
			List<CatelogTab> lstChildByParent = catelogDao.getNextLevelChildren(catelog.getIntParentCateId(), new String[]{"intParentCateId"});
			if (lstChildByParent == null || lstChildByParent.size() == 0) {
				//没有子节点了，更新父节点intHasSubCate
				catelogDao.updateParentHasSubCate(catelog.getIntParentCateId(),GenericConstants.IS_HAS_LEAF_NO);
				log.info("更新父节点"+catelog.getIntParentCateId()+"为没有子节点");
			}
		}
	}

	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public List<CatelogTab> getAllChildrenTree(UserInfoDto userInfo) {
		List<CatelogTab> allCatelogTabList = this.getAllCatelogs(userInfo
				.getIntEnterpId(), userInfo.getAppId());
		return recursivAllCatelogTree(allCatelogTabList, null, null);
	}
	
	/**
	 * 递归某企业某应用的所有分类
	 * @param allCatelogTabList
	 * @param c
	 * @param temp
	 * @return
	 * @author liuhj
	 * 2012-7-9下午10:38:44
	 */
	private List<CatelogTab> recursivAllCatelogTree(
			List<CatelogTab> allCatelogTabList, CatelogTab c,List<CatelogTab> temp) {
		if (temp == null) {
			temp = new ArrayList<CatelogTab>();
		}
		for (CatelogTab catelogTab : allCatelogTabList) {
			CatelogTab parent = catelogDao.get(catelogTab.getIntParentCateId());
			if ((c == null && parent == null)
					|| (catelogTab != null && parent == c)) {
				temp.add(catelogTab);
				List<CatelogTab> lstChildren = catelogDao
						.getNextLevelChildren(catelogTab.getIntCateId());
				if (lstChildren != null && lstChildren.size() > 0) {
					recursivAllCatelogTree(allCatelogTabList, catelogTab, temp);
				}
			}
		}
		return temp;
	}
	
	@Override
	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void update(CatelogTab obj) {
		super.update(obj);
	}
	
	/**
	 * 获取分类缩略图
	 * @param id
	 * @return
	 * @author liuhj
	 * 2012-8-3下午03:15:35
	 */
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	private String getCatelogUrl(int id){
		String[] properties = {"varCateImgUrl"};
		return catelogDao.getCatelogInfoById(id, properties).getVarCateImgUrl();
	}

	@TriggersRemove(cacheName=GenericConstants.CATELOG_EHCACHE,removeAll=true)
	public void update(String jsonData,String webAppsRealPath, String imgBasePath) {
		JSONObject jo = JSONObject.fromObject(jsonData);
		if(log.isDebugEnabled()){
			log.debug("更新分类的json请求数据:"+jo.toString());
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		CatelogTab catelog = (CatelogTab) JSONObject.toBean(jo
				.getJSONObject("catelogInfo"), CatelogTab.class);
		catelog.setVarCateImgUrl(catelog.getVarCateImgUrl().replace(getServerUrl(), ""));
		StringBuffer hql = new StringBuffer("update CatelogTab c set ");
		hql.append("c.datUpdateDatetime=:datUpdateDatetime");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("datUpdateDatetime", date);//date
		hql.append(",c.varCateName=:varCateName");
		argsMap.put("varCateName", catelog.getVarCateName());//name
		hql.append(",c.varCateDescrip=:varCateDescrip");
		argsMap.put("varCateDescrip", catelog.getVarCateDescrip());
		hql.append(",c.intPrivilege=:intPrivilege");
		argsMap.put("intPrivilege", catelog.getIntPrivilege());//privilege
		
		String currentCatelogUrl = this.getCatelogUrl(catelog.getIntCateId());
		if ("\"null\"".equals(catelog.getVarCateImgUrl())) {
			catelog.setVarCateImgUrl(null);
		}
		if (!catelog.getVarCateImgUrl().equals(currentCatelogUrl) && !StringUtils.isBlank(catelog.getVarCateImgUrl())){
			//从临时文件夹复制分类缩略图
			copyIconFromTemp(webAppsRealPath, imgBasePath, catelog);
			hql.append(",c.varCateImgUrl=:varCateImgUrl");
			argsMap.put("varCateImgUrl", catelog.getVarCateImgUrl());//img url
		}
		hql.append(" where c.intCateId=:intCateId");
		argsMap.put("intCateId", catelog.getIntCateId());
		//更新分类信息
		catelogDao.hqlOperation(hql.toString(), argsMap);
		
		JSONArray ja = JSONArray.fromObject(jo.get("attributeInfo"));
		int size = ja.size();
		for (int i = 0; i < size; i++) {
			//更新分类属性
			AttributeTab attribute = (AttributeTab) JSONObject
					.toBean(JSONObject.fromObject(ja.get(i)),AttributeTab.class);
			if (attribute.getIntAttriId() == -1) {
				//保存
				attribute.setIntCateId(catelog.getIntCateId());
				attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
				attribute.setDatUpdateDatetime(date);
				attribute.setIntInputType(GenericConstants.ATTRIBUTE_INPUT_TYPE_INPUT);
				attribute.setIntType(0);
				attributeDao.save(attribute);
				if(log.isDebugEnabled()){
					log.debug("保存分类-" + catelog.getVarCateName() + " 的属性："
							+ attribute.getVarAttriName());
				}
			} else {
				// 更新
				attributeDao.update(attribute);
				if(log.isDebugEnabled()){
					log.debug("更新分类-" + catelog.getVarCateName() + " 的属性："
							+ attribute.getVarAttriName());
				}
			}
		}
		//权限修改是否应用到子权限
		updateChildrenPrivilege(jo.getInt("isAppToChild"), catelog);
	}
	
	private void updateChildrenPrivilege(int isAppToChild,CatelogTab catelog) {
		if (isAppToChild == 1) {
			//更改子分类权限
			List<CatelogTab> children = catelogDao.getSubordinateCatelogs(catelog.getIntCateId());
			StringBuffer hql = new StringBuffer("update CatelogTab c set ");
			hql.append("c.datUpdateDatetime=:datUpdateDatetime");
			Map<String, Object> argsMap = new HashMap<String, Object>();
			argsMap.put("datUpdateDatetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//date
			hql.append(",c.intPrivilege=:intPrivilege");
			argsMap.put("intPrivilege", catelog.getIntPrivilege());//privilege
			hql.append(" where c.intCateId in(");
			for (CatelogTab catelogTab : children) {
				hql.append(catelogTab.getIntCateId()+",");
			}
			hql.deleteCharAt(hql.lastIndexOf(",")).append(")");
			//更新分类信息
			catelogDao.hqlOperation(hql.toString(), argsMap);
		}
	}

	/**
	 * 从临时文件夹复制分类缩略图
	 * @param webAppsRealPath
	 * @param imgBasePath
	 * @param catelog
	 * @author liuhj
	 * 2012-8-3下午03:29:03
	 */
	private void copyIconFromTemp(String webAppsRealPath, String imgBasePath,
			CatelogTab catelog) {
		String imgAbsolutePath = webAppsRealPath + imgBasePath
				+ ImgAndFilePath.ENTERP_CATELOG + File.separator;// 绝对路径
		String targetFileName = FileUploadUtil.generateIconName()
				+ GenericConstants.CATELOG_ICON_SUFFIX;
		String tempfilePath = webAppsRealPath
				+ catelog.getVarCateImgUrl().replace("/", File.separator);
		FileUploadUtil.copy(tempfilePath, imgAbsolutePath + targetFileName);
		catelog.setVarCateImgUrl((imgBasePath + ImgAndFilePath.ENTERP_CATELOG).replace(
						"\\", "/") + "/" + targetFileName);
		log.info("从临时目录复制分类缩略图到应用分类目录成功");
	}

	@Override
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public List<CatelogTab> getAllChildrenTreeById(Integer id) {
		List<CatelogTab> lstChildren = catelogDao.getNextLevelChildren(id);
		return recursivChildrenTree(lstChildren,null);
	}
	
	/**
	 * 根据某节点递归子分类
	 * @param children
	 * @param temp
	 * @return
	 * @author liuhj
	 * 2012-7-9下午11:16:31
	 */
	private List<CatelogTab> recursivChildrenTree(List<CatelogTab> children,List<CatelogTab> temp){
		if (temp == null) {
			temp = new ArrayList<CatelogTab>();
		}
		for (CatelogTab catelogTab : children) {
			temp.add(catelogTab);
			List<CatelogTab> lstNextChildren = catelogDao
					.getNextLevelChildren(catelogTab.getIntCateId());
			if (lstNextChildren != null && lstNextChildren.size() > 0) {
				recursivChildrenTree(lstNextChildren, temp);
			}
		}
		return temp;
	}
	/**
	 * 
	 * 获取所有的分类树信息
	 * 
	 * @return
	 * @author zhangqiaing 2012-7-10上午11:00:21
	 */
	@Override
	public List<CatelogTab> getTreeData(Integer appId) {
		StringBuffer hql = new StringBuffer("from CatelogTab c ");
		hql.append(" where c.intDeleteSign=:intDeleteSign");
		hql.append(" and c.intAppId=:appId");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("appId", appId);
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		return catelogDao.hqlGetList(hql.toString(), argsMap);
	}
	/**
	 * 根据id的信息，查找parentId等于当前id的数据有多少条记录
	 * @param id
	 * @return
	 * @author zhangqiaing
	 * 2012-7-10上午11:04:15
	 */
	@Override
	public Integer getCountById(String id) {
		StringBuffer hql = new StringBuffer("from CatelogTab c ");
		hql.append(" where c.intParentCateId=:id and c.intDeleteSign=:intDeleteSign");
		Map<String,Object> argsMap = new HashMap<String,Object>();
		argsMap.put("id", Integer.parseInt(id));
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		
		List<CatelogTab> catlogList=catelogDao.hqlGetList(hql.toString(), argsMap);	
		if(catlogList!=null){
			return catlogList.size();
		}else{
			return 0;
		}
	}
	/**
	 * 根据分类ID获得下属分类
	 * @param id
	 * @return
	 * @author zhangqiaing
	 * 2012-7-10上午11:05:44
	 */
	@Override
	public List<CatelogTab> getChildrenTreeById(String id,Integer pageNo,Integer pageSize) {
		
		StringBuffer hql = new StringBuffer("from CatelogTab c ");
		hql.append(" where c.intParentCateId=:id and c.intDeleteSign=:intDeleteSign");
		
		Map<String,Object> argsMap = new HashMap<String,Object>();
		argsMap.put("id", Integer.parseInt(id));
		
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		
		List<CatelogTab> list=catelogDao.findByHql(hql.toString(), pageNo, pageSize, argsMap);
		
		for (CatelogTab tab : list) {
			tab.setVarCateImgUrl(tab.getVarCateImgUrl() == null ? "" : (tab
					.getVarCateImgUrl().startsWith(
							GenericConstants.IMG_RELATIVE_PREFIX) ? getServerUrl() + tab.getVarCateImgUrl() : tab
					.getVarCateImgUrl()));
		}
		
		return list;
	}

	@Override
	public List<CatelogTab> getAll(UserInfoDto user) {
		return catelogDao.getAll(user);
	}

	@Override
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public CatelogTab getCatelogInfoById(int id, String[] properties) {
		return catelogDao.getCatelogInfoById(id, properties);
	}

	@Override
	@Cacheable(cacheName=GenericConstants.CATELOG_EHCACHE)
	public List<AttributeTab> getAllAttributesByCateId(int cateId) {
		List<CatelogTab> catelogs = catelogDao.getSuperiorCatelogs(cateId);
		StringBuffer cateIds = new StringBuffer("(");
		for (CatelogTab catelogTab : catelogs) {
			cateIds.append(catelogTab.getIntCateId()+",");
		}
		cateIds.deleteCharAt(cateIds.lastIndexOf(",")).append(")");
		String[] properties = {"intAttriId","varAttriName","intType","intInputType"};
		return attributeDao.getAttributesByCateId(cateIds.toString(), properties);
	}

	@Override
	public List<CatelogTab> getNextLevelChildren(int cateId) {
		String[] properties = { "intCateId", "varCateName", "intParentCateId",
				"varCateImgUrl", "intHasSubCate", "varCateDescrip" };
		return catelogDao.getNextLevelChildren(cateId, properties);
	}

	@Override
	public void deleteAttr(int attrId) {
		log.info("删除属性:"+attrId);
		//删除属性
		attributeDao.delete(attrId);
		//删除属性值
		attributeValueDao.deleteByAttrId(attrId);
		//删除被绑定的属性
		bindContentAttributeDao.deleteByAttrId(attrId);
		viewContentAttributeDao.deleteByAttrId(attrId);
		//删除被绑定的排序字段
		deleteBindingSortAttr(attrId);
	}
	
	private void deleteBindingSortAttr(int attrId) {
		StringBuffer hql = new StringBuffer();
		hql.append("update DataSortTab d set d.intDeleteSign=:intDeleteSign");
		hql.append(" where d.intIsAttr=:intIsAttr and d.intSortColumnId=:intSortColumnId");
		Map<String,Object> argMaps = new HashMap<String,Object>();
		argMaps.put("intDeleteSign",GenericConstants.DELETE_SIGN_DELETED );
		argMaps.put("intIsAttr",GenericConstants.OPTION_YES);
		argMaps.put("intSortColumnId", attrId);
		attributeDao.hqlOperation(hql.toString(), argMaps);
	}

	@Override
	public int[] getThumbPixelByBindCate(int cateId, int type) {
		int style = 6008;//800*997
		List<AppPageViewTab> l1 = appPageViewDao.getStyleByCateIdFromCateR(cateId, type);
		List<int[]> styles = new ArrayList<int[]>();
		if (l1 != null && l1.size() > 0) {
			for (AppPageViewTab appPageViewTab : l1) {
				styles.add(getWidthHeightSize(appPageViewTab.getIntModuleStyleId()));
			}
			return getMaxSize(styles);
		} else if (type != 0) {
			List<AppPageViewTab> l2 = appPageViewDao.getStyleByCateIdFromContR(cateId);
			if (l2 != null && l2.size() > 0){
				for (AppPageViewTab appPageViewTab : l2) {
					styles.add(getWidthHeightSize(appPageViewTab.getIntModuleStyleId()));
				}
				return getMaxSize(styles);
			}
		}
		return getWidthHeightSize(style);
	}
	
	private int[] getMaxSize(List<int[]> styles) {
		int max = styles.get(0)[3];
		int maxIndex = 0;
		for (int i = 1; i < styles.size(); i++) {
			if(styles.get(i)[3] > max){
				max = styles.get(i)[3];
				maxIndex = i;
			}
		}
		return styles.get(maxIndex);
	}
	
	private int[] getWidthHeightSize(int style) {
		int[] result = new int[4];
		if (style < GenericConstants.GRID_STYLE_FULL_1) {
			if (style == GenericConstants.LIST_STYLE_FULL_3 || style == GenericConstants.LIST_STYLE_HALF_3) {
				result[0] = 800;
				result[1] = 160;
				result[2] = 100;
				result[3] = 800+160;
			} else if (style == GenericConstants.LIST_STYLE_ACTIVITY) {
				result[0] = 700;
				result[1] = 350;
				result[2] = 300;
				result[3] = 700+350;
			} else {
				result[0] = 215;
				result[1] = 130;
				result[2] = 100;
				result[3] = 215+130;
			}
		} else if (style < GenericConstants.GALLERY_STYLE_FULL_1) {
			result[0] = 292;
			result[1] = 292;
			result[2] = 100;
			result[3] = 292+292;
		} else if (style < GenericConstants.GALLERY_STYLE_HALF_1) {
			result[0] = 800;
			result[1] = 997;
			result[2] = 300;
			result[3] = 800+997;
		} else {
			result[0] = 800;
			result[1] = 400;
			result[2] = 200;
			result[3] = 800+400;
		}
		return result;
	}
	
}
